//
//  OAuthController.swift
//  RacWeibo
//
//  Created by hanxu on 15/10/19.
//  Copyright © 2015年 hanxu. All rights reserved.
//

import UIKit
import ReactiveCocoa

class OAuthController: UIViewController {

    private lazy var webView = UIWebView()
    
    var userAccountVM : UserAccountViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view = webView
        webView.delegate = self
        
        setupUI()
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.OAuth))
    }
    
    override func loadView() {
        super.loadView()
    }
    
    func setupUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "后退", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }

    /// 自动填充用户信息
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '1547213@qq.com';" +
        "document.getElementById('passwd').value = 'woyai545kku';"
        
        // 执行 js 脚本
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}

extension OAuthController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        printLog(urlString!)
        
        if urlString!.containsString("http://itheima.com/?code") {
            
            let UrlString = urlString! as NSString
            let code = UrlString.substringFromIndex(25)
            ///获取用户信息
            UserAccountViewModel().loadUserInfo(code).subscribeError({ (error) -> Void in
                printLog(error)
                }, completed: { () -> Void in
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(HXSwitchRootViewControllerNotification, object: "Main")
                    })
            })
        }
        return true
    }
    
//    func webViewDidStartLoad(webView: UIWebView) {
//        printLog("开始")
//    }
//    func webViewDidFinishLoad(webView: UIWebView) {
//        printLog("结束")
//    }
//    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//        printLog("失败\(error)")
//    }
    
}
